Page({
  data:{
    isHidden:true,
  },
  onShow(){
    let userInfo = wx.getUserInfo('userinfo')
    if(userInfo && userInfo.nickName){
      this.setData({
        userInfo: userInfo
      })
    }
  },
  //获取用户头像
  getAvatar(e){
    console.log(e)
    this.setData({
      avatarUrl:e.detail.avatarUrl
    })
  },
  getName(e){
    console.log(e)
    this.setData({
      nickName:e.detail.value
    })
  },
  goLogin(){
    this.setData({
      isHidden: false
    })
  },
  //弹窗登录部分
  potNo(){
    this.setData({
      isHidden:true
    })
  },
  pop_yes(){
    let avatarUrl = this.data.avatarUrl
    let nickName = this.data.nickName
    if(!avatarUrl){
      wx.showToast({ icon:'error', title: '请获取头像', });
      return;
    }
    if(!nickName){
      wx.showToast({ icon:'error', title: '请获取昵称', });
      return;
    }
    // 上传头像到云存储
    const cloudPath = `avatars/${Date.now()}-${Math.floor(Math.random(0, 1) * 1000)}${avatarUrl.match(/.[^.]+?$/)[0]}`;
    const maxRetries = 3;
    let retryCount = 0;
    const uploadWithRetry = () => {
      wx.cloud.uploadFile({
        cloudPath,
        filePath: avatarUrl,
        success: res => {
        const cloudAvatarUrl = res.fileID;
        // 插入数据到云开发数据库的user表
        const db = wx.cloud.database();
        db.collection('user').add({
          data: {
            avatarUrl: cloudAvatarUrl,
            nickName: nickName
          },
          success: function(res) {
            console.log('数据插入成功', res);
          },
          fail: function(err) {
            console.error('数据插入失败', err);
          }
        });
        // 缓存登录状态
        let userInfo={};
        userInfo.avatarUrl=cloudAvatarUrl;
        userInfo.nickName=nickName;
        wx.setStorageSync('userinfo', userInfo);
        const app = getApp();
        app.globalData.avatarUrl = cloudAvatarUrl;
        app.globalData.nickName = nickName;
        this.setData({
          isHidden:true,
          userInfo:userInfo
        });
        // 跳转到index页面
        wx.reLaunch({
          url: '/pages/allshop/allshop'
        });
      },
      fail: err => {
          if (err.errMsg.includes('ECONNRESET') && retryCount < maxRetries) {
            retryCount++;
            setTimeout(() => uploadWithRetry(), 1000);
          } else {
            console.error('头像上传失败', err);
            wx.showToast({ icon:'error', title: `头像上传失败，请重试 (${retryCount}/${maxRetries})` });
          }
        }
      });
    };
    uploadWithRetry();
  }
})